<!-- components/DocumentGenerator.vue -->
<template>
  <div class="document-generator">
    <el-row :gutter="20">
      <!-- 表单填写区域 -->
      <el-col :span="12">
        <div class="form-section">
          <h3>填写表单信息</h3>
          <el-form :model="formData" label-width="100px" v-if="template?.form_schema?.length">
            <el-form-item
              v-for="field in template.form_schema"
              :key="field.id"
              :label="field.label"
              :prop="field.model"
              :rules="field.required ? [{ required: true, message: `请输入${field.label}` }] : []"
            >
              <!-- 动态渲染表单字段 -->
              <component-renderer :field="field" v-model="formData[field.model]" />
            </el-form-item>
          </el-form>

          <el-button type="primary" @click="generateDocument" :loading="generating">
            生成文档
          </el-button>
        </div>
      </el-col>

      <!-- 文档预览区域 -->
      <el-col :span="12">
        <div class="preview-section">
          <h3>文档预览</h3>
          <div class="preview-content" v-html="generatedContent"></div>

          <div class="preview-actions" v-if="generatedContent">
            <el-button @click="downloadDocument">下载文档</el-button>
            <el-button type="primary" @click="copyContent">复制内容</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, watch, h,inject } from 'vue'
import { ElMessage } from 'element-plus'

const api = inject('$api')

// 动态组件渲染器
const ComponentRenderer = {
  props: ['field', 'modelValue'],
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const updateValue = (value) => {
      emit('update:modelValue', value)
    }

    return () => {
      const { field } = props
      const commonProps = {
        modelValue: props.modelValue,
        'onUpdate:modelValue': updateValue,
        placeholder: field.placeholder,
        style: { width: '100%' },
      }

      switch (field.type) {
        case 'input':
          return h('el-input', commonProps)
        case 'textarea':
          return h('el-input', { ...commonProps, type: 'textarea', rows: 4 })
        case 'select':
          return h('el-select', commonProps, () =>
            field.options?.map((opt) =>
              h('el-option', {
                label: opt.label,
                value: opt.value,
              }),
            ),
          )
        case 'radio':
          return h('el-radio-group', commonProps, () =>
            field.options?.map((opt) =>
              h(
                'el-radio',
                {
                  label: opt.value,
                },
                () => opt.label,
              ),
            ),
          )
        case 'checkbox':
          return h('el-checkbox-group', commonProps, () =>
            field.options?.map((opt) =>
              h(
                'el-checkbox',
                {
                  label: opt.value,
                },
                () => opt.label,
              ),
            ),
          )
        case 'date':
          return h('el-date-picker', commonProps)
        default:
          return h('el-input', commonProps)
      }
    }
  },
}

const props = defineProps({
  template: Object,
})

const formData = ref({})
const generatedContent = ref('')
const generating = ref(false)

// 初始化表单数据
watch(
  () => props.template,
  (newTemplate) => {
    if (newTemplate?.form_schema) {
      formData.value = {}
      newTemplate.form_schema.forEach((field) => {
        formData.value[field.model] = ''
      })
    }
  },
  { immediate: true },
)

// 生成文档
const generateDocument = async () => {
  try {
    generating.value = true

    // 替换模板中的占位符
    let content = props.template.content
    Object.keys(formData.value).forEach((key) => {
      const value = formData.value[key] || ''
      const placeholder = `{{${key}}}`
      content = content.replace(new RegExp(placeholder, 'g'), value)
    })

    generatedContent.value = content.replace(/\n/g, '<br>')
  } catch (error) {
    ElMessage.error('生成文档失败')
  } finally {
    generating.value = false
  }
}

// 下载文档
const downloadDocument = () => {
  const element = document.createElement('a')
  const file = new Blob([generatedContent.value.replace(/<br>/g, '\n')], {
    type: 'text/plain',
  })
  element.href = URL.createObjectURL(file)
  element.download = `${props.template.title}.txt`
  document.body.appendChild(element)
  element.click()
  document.body.removeChild(element)
}

// 复制内容
const copyContent = async () => {
  try {
    await navigator.clipboard.writeText(generatedContent.value.replace(/<br>/g, '\n'))
    ElMessage.success('内容已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
.document-generator {
  padding: 20px;
}

.form-section,
.preview-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  min-height: 500px;
}

.preview-content {
  min-height: 400px;
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  padding: 16px;
  margin-top: 16px;
  line-height: 1.6;
  background: #fafafa;
}

.preview-actions {
  margin-top: 16px;
  text-align: center;
}
</style>
